<?php

declare(strict_types=1);

/**
 * @Author:     Frank
 * @contact     frank_hhm@163.com
 * @Date:       2023-02-02 13:10:44
 * @Last Modified time: 2023-02-15 16:08:14
 */
namespace app\api\controller\user;
use think\facade\App;
use app\common\services\user\UserAddressService;
/**
 * 用户地址
 * Class UserAddress
 * @package app\api\controller\user
 */
class UserAddress extends \app\api\controller\Base
{

    /**
     * UserAddressService constructor.
     * @param App $app
     */
    public function __construct(App $app,UserAddressService $service)
    {
        parent::__construct($app);
        $this->service = $service;
    }

    /**
     * 地址详细 
     * @method(GET)
     */
    public function detail(){
        if (!$id = $this->request->param('id')) {
            $this->error('参数错误!');
        }
        $this->success($this->service->getAddressDetail(['id'=>$id]));
    }

     /**
     * 获取地址列表
     * @method(GET)
     */
    public function list()
    {
        $this->success('获取成功',$this->service->getUserAddressList([
        	'user_id'=>$this->uid
        ]));
    }

    /**
     * 添加地址
     * @method(POST)
     */
    public function create()
    {
        $data = $this->request->postMore([
            'name',
            'phone',
            ['region',[]],
            ['is_default',0],
            'label',
            'detail',
        ]);
        $data = $this->service->getAddressRegionData($data);
        $data = $this->service->checkSave($this->uid,$data);
        if($this->service->save($data)){
            $this->success('添加成功!');
        }
        $this->error('添加失败!');
    }

    /**
     * 编辑地址
     * @method(PUT)
     */
    public function update()
    {
        if (!$id = $this->request->param('id')) {
            $this->error('参数错误!');
        }
        $data = $this->request->postMore([
            'name',
            'phone',
            ['region',[]],
            ['is_default',0],
            'label',
            'detail',
        ]);
        $data = $this->service->getAddressRegionData($data);
        $data = $this->service->checkSave($this->uid,$data);
        if($this->service->update($id,$data)){
            $this->success('保存成功!');
        }
        $this->error('保存失败!');
    }

    /**
     * 删除地址
     * @method(DELETE)
     */
    public function delete()
    {
        if (!$id = $this->request->param('id')) {
            $this->error('参数错误!');
        }
        if ($this->service->delete([
        	'id'=>$id,
        	'user_id'=>$this->uid
        ])) {
            $this->success('删除成功!');
        } 
        $this->error('删除失败!');
    }
}